package com.tao.base.handler;

import com.tao.base.exception.CommonError;
import com.tao.base.exception.LearnHubException;
import com.tao.base.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authorization.AuthorizationDeniedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(LearnHubException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result ex(LearnHubException e){
        e.printStackTrace();
        log.error("错误信息：{}",e.getMessage());
        return Result.error(e.getMessage()+"若有疑问，请联系陶虹润");
    }

    @ExceptionHandler(AuthorizationDeniedException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result ex(AuthorizationDeniedException e){
        e.printStackTrace();
        log.error("错误信息：{}",e.getMessage());
        return Result.error(e.getMessage()+"权限不足,"+"若有疑问，请联系陶虹润");
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result ex(MethodArgumentNotValidException e){
        List<String> errorMessages = new ArrayList<>();
        e.getBindingResult().getFieldErrors().stream().forEach(item -> {
            errorMessages.add(item.getDefaultMessage());
        });
        log.error("错误信息：{}",errorMessages);
        return Result.error(errorMessages.toString());
    }

    //用于处理系统执行异常
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result ex(Exception e){
        e.printStackTrace();
        log.error("错误信息：{}",e.getMessage());
        return Result.error(CommonError.UNKOWN_ERROR.getErrMessage() +"若有疑问，请联系陶虹润");
    }
}
